package com.gupt.youhd.service.impl;/*
@author name
@data 2023/6/20-16:23
*/


import com.gupt.youhd.entity.Address;
import com.gupt.youhd.entity.User;
import com.gupt.youhd.exception.BusinessException;
import com.gupt.youhd.mapper.AddressMapper;
import com.gupt.youhd.service.AddressService;
import com.gupt.youhd.util.YouHDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private YouHDUtils youHDUtils;

    @Autowired
    private AddressMapper addressMapper;


    //查询当前用户所有地址信息
    @Override
    public List<Address> getAddress(HttpServletRequest request) {
        User user = youHDUtils.getUser(request);
        List<Address> addresses = addressMapper.retrieveAddressByUserId(user.getUserId());
        log.info("查询用户地址为：{}",addresses.toString());
        return addresses;
    }

    @Override
    public void updateAddress(HttpServletRequest request,Address address) {
        if(address == null){
            throw new BusinessException("地址信息不为空哦");
        }
        User user = youHDUtils.getUser(request);
        address.setUserId(user.getUserId());
        boolean isOk = youHDUtils.isMobileNumberValid(address.getPhone());
        if(!isOk){
            throw new BusinessException("请输入正确的手机号码");
        }
        addressMapper.updateAddressByAddressId(address);
    }

    @Override
    public void insertAddress(HttpServletRequest request, Address address) {
        if(address == null){
            throw new BusinessException("地址信息不为空哦");
        }
        User user = youHDUtils.getUser(request);
        address.setUserId(user.getUserId());
        boolean isOk = youHDUtils.isMobileNumberValid(address.getPhone());
        if(!isOk){
            throw new BusinessException("请输入正确的手机号码");
        }
        addressMapper.addAddress(address);
    }

    @Override
    public void delAddress(int addressId) {
        addressMapper.delAddressByAddressId(addressId);
    }
}
